<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\UserKeepDay;
use app\admin\model\User;
use app\admin\model\UserLoginLog;
use app\admin\model\Sign;
use app\admin\model\CashOut;
use app\admin\model\AdLog;
use app\admin\model\Statistics;
use app\admin\model\TaskStatistics;
use app\admin\model\UrgeStats;
use app\admin\model\Duration;
use app\admin\model\DurationRecord;
use think\Db;

/**
 * 示例接口
 */
class Demo extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 测试方法
     *
     * @ApiTitle    (测试名称)
     * @ApiSummary  (测试描述信息)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/demo/test/id/{id}/name/{name})
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="id", type="integer", required=true, description="会员ID")
     * @ApiParams   (name="name", type="string", required=true, description="用户名")
     * @ApiParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'user_id':'int','user_name':'string','profile':{'email':'string','age':'integer'}}", description="扩展数据返回")
     * @ApiReturn   ({
         'code':'1',
         'msg':'返回成功'
        })
     */
    public function test()
    {
        $this->success('返回成功', $this->request->param());
    }

    /**
     * 无需登录的接口
     *
     */
    public function test1()
    {
        $this->success('返回成功', ['action' => 'test1']);
    }

    /**
     * 需要登录的接口
     *
     */
    public function test2()
    {
        $this->success('返回成功', ['action' => 'test2']);
    }

    /**
     * 需要登录且需要验证有相应组的权限
     *
     */
    public function test3()
    {
        $this->success('返回成功', ['action' => 'test3']);
    }

    public function keep()
    {
        $appList = Db::name('app')->where('status', 0)->column('app_id');



        $s = strtotime('2021-09-28');
        $e = strtotime('2021-11-03');
        $d = ($e-$s)/(24*3600);
        for ($i = 1; $i <= $d; $i++) {
            $date = date('Y-m-d', $s + $i*24*3600);
            foreach ($appList as  $id) {
                $this->compute($date, $id);
               // $this->compute($date, $id, 1);
            }

        }

    }
    //$type为0是新增，值为1是活跃
    //$date 日期
    private function compute($date, $app_id, $type = 0)
    {
        $dateList = [2,3,4,5,6,7,15,30,60,90];
        $strTime = strtotime($date);

        $dateTime = date('Y-m-d H:i:s', $strTime);
        //该日登录活跃的用户
        $dateUer = Db::name('user_login_log')->where('addtime','between', [$dateTime, date('Y-m-d H:i:s', $strTime + 24*3600)])->where('app_id', $app_id)->column('distinct user_id');
        if ($type == 0) {
            //新增用户
            $user = Db::name('user')->where('createtime','between', [$strTime, $strTime + 24*3600])->where('app_id', $app_id)->column('id');
        } else {
            //活跃用户
            $user = $dateUer;
        }

        UserKeepDay::insert(array(
            'day_register' => $date,
            'app_id' => $app_id,
            'num' => count($user),
            'type' => $type,
            'createtime' => time()
        ));
        //循环要计算留存的日期
        foreach ($dateList  as $v) {
            $i = $v-1;
            //留存日期
            $day_register = date('Y-m-d', $strTime - $i*24*60*60);

            $day = "day{$v}";
            $scale = "scale{$v}";

            //判断留存日期是否存在新增或者登录活跃的用户
            $ret = Db::name('user_keep_day')->where('day_register', $day_register)->where('app_id', $app_id)->where('type', $type)->find();
            if (!$ret || $ret[$day] != null) {
                continue;
            }

            if ($type == 0) {
                //留存日的新增用户
                $keepUser = Db::name('user')->where('createtime','between', [strtotime($day_register), strtotime($day_register) + 24*60*60])->where('app_id', $app_id)->column('id');

            } else {
                //留存日的登录活跃用户
                $keepUser = Db::name('user_login_log')->where('addtime','between', [date('Y-m-d H:i:s', strtotime($day_register)), date('Y-m-d H:i:s', strtotime($day_register) + 24*60*60)])->where('app_id', $app_id)->column('distinct user_id');
            }


            //留存人数，留存人数等于当日新增或者活跃的用户，在date日期这一天继续登录活跃的人数
            if (!$keepUser || !$dateUer) {
                $data[$day] = 0;
                $data[$scale] = 0;
            } else {
                //当日留存的人数
                $num = count(array_intersect($keepUser, $dateUer));
                $data[$day] = $num;
                //留存率登录date日期登录的人除以留存日的登录用户或者新增用户
                $data[$scale] = $num > 0 ? $num/$ret['num'] : 0;

            }
            UserKeepDay::where('id', $ret['id'])->update($data);

        }
    }

}
